# encoding: utf-8

from flask import Flask, render_template
from bluelog.settings import config
import os
from bluelog.extensions import bootstrap, db, moment, ckeditor
from bluelog.commands import cregister_commands
from bluelog.blueprints.blog import blog_bp
from bluelog.models import Admin, Category


def create_app(config_name=None):
    if config_name is None:
        config_name = os.getenv('FLASK_CONFIG', 'development')

    app = Flask('bluelog')
    app.config.from_object(config[config_name])

    app.jinja_env.trim_blocks = True
    app.jinja_env.lstrip_blocks = True

    # register_logging(app)
    # register_extensions(app)
    register_blueprints(app)
    # register_commands(app)
    # register_errors(app)
    # register_shell_context(app)
    # register_template_context(app)
    return app


def register_logging(app):
    pass


def register_extensions(app):
    bootstrap.init_app(app)
    db.init_app(app)
    moment.init_app(app)
    ckeditor.init_app(app)
    # mail.init_app(app)


def register_blueprints(app):
    app.register_blueprint(blog_bp)


def register_shell_context(app):
    @app.shell_context_processor
    def make_shell_context():
        return dict(db=db)


def register_template_context(app):
    @app.context_processor
    def make_template_context():
        return dict()


def register_errors(app):
    @app.errorhandler(404)
    def bad_request(e):
        return render_template('errors/404.html'), 404

    @app.errorhandler(500)
    def bad_request(e):
        return render_template('errors/500.html'), 500


def register_commands(app):
    cregister_commands(app)
